package day02;

import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
import untils.IntSource;

public class Example7 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new IntSource())
                .keyBy(r -> 1)
                .process(new IntStatistic())
                .print();


        env.execute();
    }

    public static class IntStatistic extends KeyedProcessFunction<Integer,Integer,Statistics>{

        private ValueState<Statistics> accumulator;
        private ValueState<Long> timerTs;


        @Override
        public void open(Configuration parameters) throws Exception {

            accumulator = getRuntimeContext().getState(new ValueStateDescriptor<Statistics>("acc", Types.POJO(Statistics.class)));
            timerTs = getRuntimeContext().getState(new ValueStateDescriptor<Long>("time_ts",Types.LONG));
        }

        @Override
        public void processElement(Integer value, Context ctx, Collector<Statistics> out) throws Exception {
            if (accumulator.value() == null){
                accumulator.update(
                        new Statistics(
                                value,
                                1,
                                value,
                                value,
                                value
                        )
                );
            }
            else {
                Statistics tmp = accumulator.value();
                accumulator.update(
                        new Statistics(
                                tmp.sum + value,
                                tmp.count + 1,
                                (tmp.sum + value) / (tmp.count + 1),
                                Math.min(tmp.min, value),
                                Math.max(tmp.max, value)
                        )
                );
            }

            if (timerTs.value() == null){
                long tenSecLater = ctx.timerService().currentProcessingTime() + 10 * 1000L;
                ctx.timerService().registerProcessingTimeTimer(tenSecLater);
                timerTs.update(tenSecLater);
            }

        }

        @Override
        public void onTimer(long timestamp, OnTimerContext ctx, Collector<Statistics> out) throws Exception {
            if (accumulator.value() != null) out.collect(accumulator.value());
            // 清空状态变量
            timerTs.clear();
        }
    }
    public static class Statistics {

        public Integer sum;
        public Integer count;
        public Integer avg;
        public Integer min;
        public Integer max;

        public Statistics () {
        }

        public Statistics(Integer sum, Integer count, Integer avg, Integer min, Integer max) {
            this.sum = sum;
            this.count = count;
            this.avg = avg;
            this.min = min;
            this.max = max;
        }

        @Override
        public String toString() {
            return "Statistics{" +
                    "sum=" + sum +
                    ", count=" + count +
                    ", avg=" + avg +
                    ", min=" + min +
                    ", max=" + max +
                    '}';
        }
    }
}
